﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;




namespace DZJIFC.Model.Native
{
    internal static class IfcDllResolver
    {
        private static bool _inited;

        /// <summary>把 DllImport 解析绑定到声明 P/Invoke 的程序集</summary>
        internal static void InitFor(Assembly pInvokeAssembly, string subdir = "native")
        {
            if (_inited) return;
            _inited = true;

            NativeLibrary.SetDllImportResolver(pInvokeAssembly, Resolve);

            // 把本机 DLL 目录加入当前进程 PATH，方便传递依赖解析
            var baseDir = AppContext.BaseDirectory;
            var arch = Environment.Is64BitProcess ? "win-x64" : "win-x86";
            var nativeDir = Path.Combine(baseDir, subdir, arch);
            if (Directory.Exists(nativeDir))
            {
                var path = Environment.GetEnvironmentVariable("PATH") ?? "";
                if (!path.Split(';', StringSplitOptions.RemoveEmptyEntries)
                        .Any(p => string.Equals(p, nativeDir, StringComparison.OrdinalIgnoreCase)))
                {
                    Environment.SetEnvironmentVariable("PATH", nativeDir + ";" + path);
                }
            }
        }

        private static IntPtr Resolve(string libName, Assembly _, DllImportSearchPath? __)
        {
            // 你的 DllImport 常量是 "IFCEngine.dll"；这里大小写不敏感都兼容
            if (!libName.Equals("ifcengine.dll", StringComparison.OrdinalIgnoreCase) &&
                !libName.Equals("IFCEngine.dll", StringComparison.OrdinalIgnoreCase))
                return IntPtr.Zero;

            var baseDir = AppContext.BaseDirectory;
            var arch = Environment.Is64BitProcess ? "win-x64" : "win-x86";

            // 1) EXE 同级
            var path1 = Path.Combine(baseDir, "ifcengine.dll");
            if (File.Exists(path1) && NativeLibrary.TryLoad(path1, out var h1)) return h1;
            var path1b = Path.Combine(baseDir, "IFCEngine.dll");
            if (File.Exists(path1b) && NativeLibrary.TryLoad(path1b, out var h1b)) return h1b;

            // 2) native\{arch}
            var path2 = Path.Combine(baseDir, "native", arch, "ifcengine.dll");
            if (File.Exists(path2) && NativeLibrary.TryLoad(path2, out var h2)) return h2;
            var path2b = Path.Combine(baseDir, "native", arch, "IFCEngine.dll");
            if (File.Exists(path2b) && NativeLibrary.TryLoad(path2b, out var h2b)) return h2b;

            // 3) 让默认机制继续（PATH/System32）
            return IntPtr.Zero;
        }
    }
}
